<template>
  <el-card shadow="always" style="margin: 30px">
    <el-form :inline="true">
      <el-form-item prop="username">
        <el-input
          clearable
          size="mini"
          v-model="paramsSearch.username"
          placeholder="用户名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit"
          icon="el-icon-search"
          size="mini"
          >查询</el-button
        >
        <el-button type="info" @click="reset" size="mini">清空</el-button>
      </el-form-item>
    </el-form>
    <div style="margin: 20px 0">
      <el-button type="primary" @click="add" size="mini">添加</el-button>
      <el-button
        type="danger"
        @click="deleteAll"
        size="mini"
        :disabled="!userCheckedList.length"
        >批量删除</el-button
      >
    </div>
    <el-table
      v-loading="loading"
      align="center"
      border
      ref="getTable"
      :data="userInfoList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        fixed
        type="selection"
        width="60"
        align="center"
      ></el-table-column>
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="200"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="nickName"
        label="用户昵称"
        width="200"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色列表"
        align="center"
        width="400"
      >
      </el-table-column>
      <el-table-column
        prop="gmtCreate"
        label="创建时间"
        width="200"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="gmtModified"
        label="更新时间"
        width="200"
        align="center"
      >
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="400">
        <template slot-scope="scope">
          <el-button
            @click="setUserRole(scope.row)"
            type="info"
            size="mini"
            title="分配角色"
            icon="el-icon-user-solid"
          ></el-button>
          <el-button
            title="修改用户"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="changeUserName(scope.row)"
          ></el-button>
          <!-- <el-popconfirm :title="`确定删除 ${scope.row.username} 吗?`" @confirm="() =>removeUser(scope.row.id)"> -->
          <el-button
            slot="reference"
            title="删除用户"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            style="margin-left: 10px"
            @click="removeUser(scope.row.id)"
          ></el-button>
          <!-- </el-popconfirm> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加修改对话框 -->
    <el-dialog
      :title="addUserForm.id ? '修改用户' : '添加用户'"
      :visible.sync="addOrUpdateDialog"
      width="30%"
      :before-close="addOrUpdateBeforeClose"
    >
      <el-form
        ref="addOrUpdateForm"
        :model="addUserForm"
        :rules="rules"
        :label-position="'right'"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="addUserForm.nickName"></el-input>
        </el-form-item>

        <el-form-item label="用户密码" prop="password" v-if="!addUserForm.id">
          <el-input v-model="addUserForm.password" show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addOrUpdateCancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="设置角色"
      :visible.sync="setRoleDialog"
      width="30%"
      :before-close="setUserRoleCloseBefore"
    >
      <el-form :label-position="'right'" label-width="100px">
        <el-form-item label="用户名">
          <el-input
            v-model="addUserForm.username"
            size="small"
            :disabled="true"
          ></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox
            label="全选"
            v-model="roleListInfo.checkAll"
            :indeterminate="isAllChecked"
            @change="changeCheckedAll"
          ></el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-checkbox-group v-model="roleListInfo.roleList">
            <el-checkbox
              :label="role.id"
              @click="changeRoleChecked"
              v-for="(role, index) in roleListInfo.allRoleList"
              :key="role.id"
              >{{ role.roleName }}</el-checkbox
            >
            <!-- <el-checkbox label="地推活动"></el-checkbox>
            <el-checkbox label="线下主题活动"></el-checkbox>
            <el-checkbox label="单纯品牌曝光"></el-checkbox> -->
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setUserRoleCancel">取 消</el-button>
        <el-button type="primary" @click="setUserRoleConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-pagination
      style="margin-top: 40px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="paramsSearch.page"
      :page-sizes="[5, 10, 15]"
      :page-size="paramsSearch.limit"
      layout="prev, pager, next, jumper,->, sizes, total"
      :total="total"
    >
    </el-pagination>
  </el-card>
</template>
<script>
import {
  getUserListApi,
  addOrUpdateUserApi,
  getUserRoleListApi,
  deleteUserApi,
  assignUserRoleListApi,
} from "@/api/acl/userInfo";
import { Message } from "element-ui";
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "User",
  data() {
    return {
      // 查询用户名
      paramsSearch: {
        searchUserName: "",
        username: "",
        // 当前页
        limit: 5,
        // 呈现数据的数量
        page: 1,
      },
      // 整理请求回来的数据
      userInfoList: [],
      // 选中用户数组
      userCheckedList: [],
      // 获取表单添加用户的信息
      addUserForm: {
        id: "",
        username: "",
        password: "",
        nickName: "",
      },
      // 分配角色列表
      roleListInfo: {
        roleList: [],
        allRoleList: [],
        checkAll: false,
      },
      // 没有选中状态的情况下
      isAllChecked: true,
      // 表格加载中
      loading: false,
      // 添加和修改的对话框
      addOrUpdateDialog: false,
      // 分配角色对话框
      setRoleDialog: false,
      // 总数
      total: 10,
      // 表格展示的静态数据
      // tableData: [
      //   {
      //     id: 1,
      //     userName: "111",
      //     nickName: "视口的和罚款",
      //     roleName: ["dhk", "ef", "ii"],
      //     password: "666666",
      //   },
      //   {
      //     id: 2,
      //     userName: "111",
      //     nickName: "视口的和罚款",
      //     roleName: ["dhk", "ef", "ii"],
      //     password: "666666",
      //   },
      //   {
      //     id: 3,
      //     userName: "111",
      //     nickName: "视口的和罚款",
      //     roleName: ["dhk", "ef", "ii"],
      //     password: "666666",
      //   },
      //   {
      //     id: 4,
      //     userName: "111",
      //     nickName: "视口的和罚款",
      //     roleName: ["dhk", "ef", "ii"],
      //     password: "666666",
      //   },
      // ],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 18,
            message: "用户名长度必须在 3 到 18 ",
            trigger: "blur",
          },
        ],
        nickName: [{ message: "请输入昵称", trigger: "blur" }],
        password: [
          {
            required: true,
            min: 6,
            max: 20,
            message: "密码长度必须在6到20",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    // 获取分页列表数据
    async getUserList() {
      // const { page, limit } = this.paramsSearch;

      try {
        this.loading = true;
        const result = await getUserListApi(
          this.paramsSearch.page,
          this.paramsSearch.limit,
          this.paramsSearch.searchUserName
        );
        console.log(result);
        this.userInfoList = result.data.items;
        this.total = result.data.total;
        this.loading = false;
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 头部按钮

    // 点击查询按钮
    onSubmit() {
      this.paramsSearch.searchUserName = this.paramsSearch.username;
      this.getUserList(1);
    },
    // 点击清空按钮
    reset() {
      this.paramsSearch.username = "";
      this.paramsSearch.searchUserName = this.paramsSearch.username;
      this.getUserList(1);
    },
    // 点击添加按钮
    add() {
      console.log(this.$refs);
      console.log("111", this.addUserForm.id);
      if (this.$refs.addOrUpdateForm) {
        this.$refs.addOrUpdateForm.resetFields();
      }
      // 表单数据中是没有id的，在需要的地方手动清空
      this.addUserForm.id = "";
      // 因为修改对话框中的表单是没有密码框的，此时需要自己手动清空密码
      this.addUserForm.password = "";
      this.addOrUpdateDialog = true;
    },
    // 点击批量删除按钮
    deleteAll() {
      if (this.userCheckedList.length) {
        this.userCheckedList.forEach(async (item) => {
          await deleteUserApi(item.id);
        });
      }
      this.getUserList();
    },
    // 点击修改用户按钮
    changeUserName(user) {
      console.log("数据回显", user);
      this.addUserForm = cloneDeep(user);
      this.addOrUpdateDialog = true;
    },

    // 表格选中状态改变的事件
    handleSelectionChange(val) {
      this.userCheckedList = val;
      // console.log(val)
    },

    // 添加和修改对话框

    // 点击添加或修改的对话框取消按钮
    addOrUpdateCancel() {
      // this.addUserForm = resetForm()
      // this.addUserForm.username = "";
      // this.addUserForm.nickName = "";
      // this.addUserForm.password = "";
      // this.addUserForm.id = "";
      if (this.$refs.addOrUpdateForm) {
        this.$refs.addOrUpdateForm.resetFields();
      }
      this.addOrUpdateDialog = false;
    },
    // 点击添加或修改的对话框确定按钮
    addOrUpdateConfirm() {
      console.log(111);
      this.$refs.addOrUpdateForm.validate(async (val, error) => {
        if (val) {
          await addOrUpdateUserApi(this.addUserForm);
          if (this.$refs.addOrUpdateForm) {
            this.$refs.addOrUpdateForm.resetFields();
          }
          this.addOrUpdateDialog = false;
          this.getUserList();
          console.log(222);
        } else {
          Message.error("请输入内容");
        }
      });
    },
    // 点击添加或修改用户对话框关闭前事件 ×
    addOrUpdateBeforeClose() {
      if (this.$refs.addOrUpdateForm) {
        this.$refs.addOrUpdateForm.resetFields();
      }

      // this.addUserForm.username = "";
      // this.addUserForm.nickName = "";
      // this.addUserForm.password = "";
      // this.addUserForm.id = "";
      this.addOrUpdateDialog = false;
    },

    // 分配角色对话框

    // 点击分配角色按钮
    async setUserRole(row) {
      console.log(row);
      this.addUserForm = row;
      this.setRoleDialog = true;
      try {
        const result = await getUserRoleListApi(row.id);
        console.log(result);
        const { allRolesList, assignRoles } = result.data;
        // id数组
        this.roleListInfo.roleList = assignRoles.map((item) => item.id);

        this.roleListInfo.allRoleList = allRolesList;

        this.roleListInfo.checkAll = allRolesList.length === assignRoles.length;

        this.isIndeterminate =
          assignRoles.length > 0 && assignRoles.length < allRolesList.length;
        return "ok";
      } catch (error) {
        return Promise.reject(error);
      }
    },

    resetRoleData() {
      Object.assign(this.roleListInfo, {
        allRolesList: [],
        roleList: [],
        checkAll: false,
      });
      this.isAllChecked = false;
      this.setRoleDialog = false;
    },
    // 全选角色列表
    changeCheckedAll(val) {
      console.log('111',val)
      this.roleListInfo.roleList = val
        ? this.roleListInfo.allRoleList.map((item) => item.id)
        : [];
        this.isAllChecked = false;
     
    },
    // 选中角色单项列表
    changeRoleChecked(value) {
      let checkedCount = value.length;
      this.roleListInfo.checkAll =
        checkedCount === this.roleListInfo.allRoleList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roleListInfo.allRoleList.length;
    },
    // 点击设置角色关闭对话框前事件
    setUserRoleCloseBefore() {
      this.resetRoleData();
      this.setRoleDialog = false;
    },
    // 点击设置角色取消对话框按钮
    setUserRoleCancel() {
      this.resetRoleData();
      this.setRoleDialog = false;
    },
    // 点击设置角色确定对话框按钮
    async setUserRoleConfirm() {
      const userId = this.addUserForm?.id;
      console.log(userId)
      const roleIds = this.roleListInfo.roleList.join(",");
      console.log(typeof roleIds)
      await assignUserRoleListApi(userId, roleIds);
      console.log('分别')
      Message.success("分配角色成功");
      this.resetRoleData();
      this.getUserList()
    },

    // 分页器

    // 改变页面呈现数据大小事件
    handleSizeChange(val) {
      this.paramsSearch.limit = val;
      this.getUserList();
    },
    // 改变当前页事件
    handleCurrentChange(val) {
      this.paramsSearch.page = val;
      this.getUserList();
    },
    // 操作单个删除用户按钮
    async removeUser(id) {
      try {
        console.log("单个删除");
        await deleteUserApi(id);
        console.log("删除成功");
        this.getUserList();
        return "ok";
      } catch (error) {
        console.log("删除");
        return Promise.reject(error);
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
